

"""
用Python爬取豆瓣电影正在上映的电影信息
标题
链接
评分
简介

"""

import tkinter as tk
import requests
from tkinter import messagebox
import parsel
def search_douban():
    # 获取输入框内容
    query = entry.get()
    if not query:
        messagebox.showwarning("输入错误", "请输入搜索内容")
        return

    url = f"https://search.douban.com/movie/subject_search?search_text={query}"
    try:
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
                          " (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
        }
        response = requests.get(url, headers=headers)
        print(response.text)

        # 解析网页内容
        selector = parsel.Selector(response.text)
        # 找到所有电影的标题、链接、评分、简介
        titles = selector.css(".title::text").getall()
        links = selector.css(".title").xpath('@href').getall()
        scores = selector.css(".rating_num::text").getall()
        introductions = selector.css(".inq::text").getall()
        # 打印结果
        for i in range(len(titles)):
            print(f"标题：{titles[i]}")
            print(f"链接：{links[i]}")
            print(f"评分：{scores[i]}")
            print(f"简介：{introductions[i]}")
            print("\n")
    #     捕获在进行网络请求时可能出现的异常
    # 这是requests库中定义的一个基类异常，所有与请求相关的异常都继承自这个类。它可以捕获多种请求错误，例如连接错误、超时错误、HTTP错误等
    except requests.exceptions.RequestException as e:
        messagebox.showerror("错误", e)
# 创建主窗口
root = tk.Tk()
root.title("豆瓣搜索")

# 创建要提示输入内容的标签
label = tk.Label(root, text="请输入您要搜索的内容", anchor='w')
label.pack(fill='x', pady=5)
# 创建输入框
entry = tk.Entry(root, width=50)
entry.pack(pady=20)

# 创建搜索按钮
search_button = tk.Button(root, text="搜索", command=search_douban)
search_button.pack(pady=10)

# 运行主循环
root.mainloop()


